{extend name="main"}
{block name="style"}
<style type="text/css">
    .flex-lable {
        width: 120px;
        color: #6c757d;
        text-align: right;
        padding-right: 10px;
    }

    .el-image-viewer__img {
        transition: all .3s;
        -moz-transition: all .3s;
        -webkit-transition: all .3s;
        -o-transition: all .3s;
    }

    .w-400px {
        width: 400px !important;
    }

    .status {
        position: absolute;
        right: 5px;
        top: 5px;
        background-color: #FFF;
        border: solid 1px #FF6D06;
        color: #FF6D06;
        width: 60px;
        height: 20px;
        line-height: 18px;
        text-align: center;
        border-radius: 10px;
        z-index: 100;
    }

    .status.success {
        border: solid 1px #28a745;
        color: #28a745;
    }

    .status.danger {
        border: solid 1px #dc3545;
        color: #dc3545;
    }

    .checkbox-id {
        position: absolute;
        left: 5px;
        top: 5px;
    }

    .checkbox-id .el-checkbox__label {
        display: none;
    }
</style>
{/block}
{block name="body"}
<div class="bg-white p-3">
    <div class="table-responsive py-3 flex">
        <el-upload ref="upload" :file-list="fileList" :show-file-list="false" :auto-upload="false" :multiple="false"
            :on-change="readXlsx">
            <el-button slot="trigger" type="primary" size="mini">
                导入({{tableData.length}})
            </el-button>
        </el-upload>

        <el-button type="primary" size="mini" @click="window.open('/resume/addResume')" plain
            style="margin-left: 10px;">手动添加简历</el-button>
        <el-button type="success" size="mini" @click="submitResumes" plain>批量提交</el-button>
        <el-button type="info" size="mini" @click="showSuccessNumber" plain>
            可导入：(<span>{{effectiveNumber}}</span>)&nbsp;|&nbsp;已成功：(<span>{{successNumber}}</span>)
        </el-button>
    </div>
    <div class="table-responsive py-3 flex">导入模板及注意事项请&nbsp;<a target="_blank"
            href="https://www.xycms.com/contact_us.html">联系客服领取</a></div>
    <div class="table-responsive">
        <el-table ref="tableList" :data="tableData" style="width: 100%;" header-cell-class-name="table-header-DDE6FB"
            @expand-change="getResumeInfo" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" :selectable="checkSelectable">
            </el-table-column>
            <el-table-column label="详情" width="50">
                <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" :content="scope.row.errMsg ? scope.row.errMsg : '此数据有效'" placement="top-start">
                        <i v-if="scope.row.invalid" class="el-icon-warning pointer text-danger h5 mb-0"></i>
                        <i v-else-if="!scope.row.invalid&&scope.row.errMsg" class="el-icon-question pointer text-warning h5 mb-0"></i>
                        <i v-else class="el-icon-success pointer text-success h5 mb-0"></i>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="姓名" width="160">
                <template slot-scope="scope">
                    <div>
                        <el-link type="primary" :href="'/resume/find/'+scope.row.id" target="_blank" :underline="false"
                            title="浏览">{{scope.row.name}}</el-link>
                        <div>{{scope.row.mobile}}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="基本信息" min-width="100">
                <template slot-scope="scope">
                    <div class="small">
                        <div class="flex text-nowrap flex-center font-weight-bold">
                            <div>{{XYBase.Date.getMStoYear(scope.row.age*1000)}}岁</div>
                            <div class="mx-1">·</div>
                            <div v-if="scope.row.sex==1">男</div>
                            <div v-else-if="scope.row.sex==2">女</div>
                            <div v-else="scope.row.sex">未设置</div>
                            <div class="mx-1">·</div>
                            <div>{{scope.row.educational_background}}</div>
                            <div class="mx-1">·</div>
                            <div>{{XYBase.Date.getMStoYear(scope.row.work_experience_time*1000)}}年经验</div>
                        </div>
                        <div class="flex text-nowrap flex-center" v-for="v in scope.row.ResumeEmploymentIntention">
                            <div class="text-2d91f0">{{v.jobs_cate3}}</div>
                            <div class="border-left py-1 mx-1"></div>
                            <div>{{v.industry?v.industry:'行业不限'}}</div>
                            <div class="border-left py-1 mx-1"></div>
                            <div v-if="v.area_city">{{v.area_city}}{{v.area_area}}</div>
                            <div v-else>地区不限</div>
                            <div class="border-left py-1 mx-1"></div>
                            <div v-if="v.salary_min>0">{{v.salary_min}}~{{v.salary_max}}k</div>
                            <div v-else>面议</div>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="求职状态">
                <template slot-scope="scope">
                    <div>
                        {{scope.row.job_status}}
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="自我描述">
                <template slot-scope="scope">
                    <div>
                        {{scope.row.self_description}}
                    </div>
                </template>
            </el-table-column>
        </el-table>
    </div>
</div>
{/block}

{block name="script"}
{js href="__PLUGIN_SRC__/Xlsx/xlsx.core.min.js"}
{js href="__PLUGIN_SRC__/Xlsx/xlsx.utils.min.js"}

<script type="text/javascript">
    var hwdn = null;
    var vm = new Vue({
        el: '#app',
        data: {
            view: XYBase.view,
            labelPosition: 'right',
            showLog: false,
            dialogVisible: false,
            successNumber: 0,
            tableData: [],
            fileList: [],
            fileReader: {}
        },
        watch: {
            view: XYBase.viewWatch,
        },
        computed: {
            effectiveNumber() {
                let result = 0;
                for (let i = 0; i < this.tableData.length; i++) {
                    if (this.tableData[i].invalid != undefined && this.tableData[i].invalid == false) {
                        result++;
                    }
                }
                return result;
            }
        },
        created() {
            XYBase.created(this);
        },
        methods: {
            handleSelectionChange() {

            },
            readXlsx(e) {
                let _this = this;
                file = e.raw;
                let fileReader = new FileReader();

                fileReader.onload = function (ev) {
                    try {
                        var data = ev.target.result,
                            // 以二进制流方式读取整份excel表格对象
                            workbook = XLSX.read(data, {
                                type: 'binary'
                            });
                    } catch (e) {
                        XYBase.error('文件类型不正确');
                        return;
                    }

                    // 表格的表格范围，可用于判断表头是否数量是否正确
                    let fromTo = '';
                    /* 
                      遍历每张工作表
                      sheet是Sheets这个对象属性的key，Sheets则是Excel文件中所有的工作表(每个工作表则是这个对象的属性)
                    */

                    _this.tableData = [];
                    for (let sheet in workbook.Sheets) {
                        // 获取表头最后一列的坐标
                        fromTo = workbook.Sheets[sheet]['!ref'];
                        // 获取出表格中(不为空)的数据，属性名则是表头的对应列
                        let content = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
                        for (let index = 0; index < content.length; index++) {
                            let row = _this.buildResumeData(content[index]);
                            _this.tableData.push(row)
                        }
                        // 只读取第一个工作表，所以只循环一次
                        break;
                    }
                    // 通过接口校验读取出来的数据
                    _this.checkAllData()
                };
                fileReader.readAsBinaryString(file);
            },
            buildResumeData(row) {
                // 开始初步校验
                let data = {
                    invalid: false,
                    errMsg: '',
                    employment_intention: [],
                    educational_experience: [],
                    work_experience: [],
                    training_experience: [],
                    project_experience: [],
                    certificate: [],
                    language_ability: [],
                    specialty_label: []
                };
                try {
                    // 姓名是否存在
                    if (row['姓名'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '姓名不能为空';
                    } else {
                        data.name = row['姓名'];
                    }
                    if (row['性别'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '性别不能为空';
                    } else {
                        data.sex = row['性别'] == '男' ? 1 : 2;
                    }
                    if (row['出生年月'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '出生年月';
                    } else {
                        data.age = Math.round(new Date(row['出生年月']).getTime() / 1000);
                    }
                    if (row['最高学历'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '最高学历不能为空';
                        return data;
                    } else {
                        data.educational_background = row['最高学历'];
                    }
                    if (row['参加工作时间'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '参加工作时间不能为空';
                        return data;
                    } else {
                        data.work_experience_time = Math.round(new Date(row['参加工作时间']).getTime() / 1000);
                    }
                    if (row['求职状态'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '求职状态不能为空';
                        return data;
                    } else {
                        data.job_status = row['求职状态'];
                    }
                    if (row['手机号'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '手机号不能为空';
                        return data;
                    } else {
                        data.mobile = row['手机号'];
                    }
                    if (row['工作性质'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '求职意向(工作性质)不能为空';
                        return data;
                    }
                    if (row['期望工作地区'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '求职意向(期望工作地区)不能为空';
                        return data;
                    }
                    if (row['期望行业'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '求职意向(期望行业)不能为空';
                        return data;
                    }
                    if (row['期望职位类别'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '求职意向(期望职位类别)不能为空';
                        return data;
                    }
                    if (row['期望薪资'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '求职意向(期望薪资)不能为空';
                        return data;
                    }
                    if (row['居住地'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '居住地不能为空且必须是省市两级关系';
                        return data;
                    } else {
                        let residenceArea = row['居住地'].split('>');
                        if (residenceArea.length < 2) {
                            data.invalid = true;
                            data.errMsg = '居住地格式错误'
                        }
                        data.residenceArea1 = residenceArea[0];
                        data.residenceArea2 = residenceArea[1];
                    }
                    if (row['籍贯'] == undefined) {
                        data.invalid = true;
                        data.errMsg = '籍贯不能为空且必须是省市两级关系';
                        return data;
                    } else {
                        let nativePlaceArea = row['籍贯'].split('>');
                        if (nativePlaceArea.length < 2) {
                            data.invalid = true;
                            data.errMsg = '居住地格式错误'
                            return data;
                        }
                        data.nativePlaceArea1 = nativePlaceArea[0];
                        data.nativePlaceArea2 = nativePlaceArea[1];
                    }
                    if (row['所学专业'] != undefined) {
                        data.specialities = row['所学专业']
                    }
                    if (row['自我描述'] != undefined) {
                        data.self_description = row['自我描述']
                    }

                    /* 求职意向 */
                    let empIntWorkNature = row['工作性质'].split('||');
                    let empIntWorkArea = row['期望工作地区'].split('||');
                    let empIntWorkIndustry = row['期望行业'].split('||');
                    let empIntWorkJobCate = row['期望职位类别'].split('||');
                    let empIntWorkSalary = row['期望薪资'].split('||');
                    /* 如果解析出来的求职意向不到一个 */
                    if (empIntWorkNature.length < 1 ||
                        empIntWorkArea.length < 1 ||
                        empIntWorkIndustry.length < 1 ||
                        empIntWorkJobCate.length < 1 ||
                        empIntWorkSalary.length < 1) {
                        // 任意求职意向必填解析出来少于1个则将这条数据设置为无效
                        data.invalid = true;
                        data.errMsg = '求职意向无效(无法从当前格式匹配出求职意向)';
                        return data;
                    }
                    // 求职意向最多三个
                    let effectiveEmpInt = 0;
                    for (let i = 0; i < empIntWorkNature.length && i < 3; i++) {
                        if (effectiveEmpInt == 3) break;
                        try {
                            // 初始化求职意向
                            let item = {};
                            // 工作性质
                            item.nature_of_work = empIntWorkNature[i];
                            // 工作地区
                            let workArea = empIntWorkArea[i].split('>');
                            item.job_area1 = workArea[0];
                            item.job_area2 = workArea[1];
                            item.job_area3 = workArea[2];
                            // 期望行业
                            item.industry_id = empIntWorkIndustry[i];
                            // 职位类型
                            let jobCates = empIntWorkJobCate[i].split('>');
                            item.jobscate1 = jobCates[0];
                            item.jobscate2 = jobCates[1];
                            item.jobscate3 = jobCates[2];
                            // 期望薪资(如果拆出来的数组长度小于2则视为面议，如果在长度大于等于2的数组中无法匹配到以k为单位的1~3位数也视为面议)
                            let salary = empIntWorkSalary[i].split('-');
                            let salaryRegex = /[0-9]{1,3}/;
                            item.salary_min = salary.length < 2 ? 0 : salaryRegex.test(salary[0]) ? salaryRegex.exec(salary[0])[0] : 0;
                            item.salary_max = salary.length < 2 ? 100 : salaryRegex.test(salary[1]) ? salaryRegex.exec(salary[1])[0] : 100;
                            data.employment_intention.push(item);
                            effectiveEmpInt++;
                        } catch (ex) {
                            console.log('求职意向存在问题：', ex);
                        }
                    }
                    if (effectiveEmpInt < 1) {
                        data.invalid = true;
                        data.errMsg = `求职意向无效(无法匹配出有效的求职意向)`;
                    }

                    // 如果存在教育经历
                    if (row['教育经历'] != undefined) {
                        let eduExp = row['教育经历'].split('||');
                        for (let i = 0; i < eduExp.length; i++) {
                            let item = {};
                            try {
                                // 将教育经历的各个参数拆解出来
                                let params = eduExp[i].split('**');
                                if (params.length < 3) {
                                    // 不到3个说明格式错误
                                    continue;
                                }
                                item.school_name = params[0];
                                item.educational_background = params[1];
                                item.specialities = params[2];
                                let time = params[3].split('-');
                                // 就读时间不完整
                                if (time.length < 2) {
                                    continue;
                                }
                                if (new Date(time[0]).getTime() == NaN || new Date(time[1]).getTime() == NaN) {
                                    continue;
                                }

                                item.start_time = Math.round(new Date(time[0]).getTime() / 1000);
                                item.end_time = Math.round(new Date(time[1]).getTime() / 1000);
                                data.educational_experience.push(item);
                            } catch (ex) {
                                data.errMsg += data.errMsg.length > 0 ? ` | 教育经历${i + 1}存在问题：${ex}` : `教育经历${i + 1}存在问题：${ex}`
                            }
                        }
                    }
                    // 如果存在工作经历
                    if (row['工作经历'] != undefined) {
                        let workExp = row['工作经历'].split('||');
                        for (let i = 0; i < workExp.length; i++) {
                            try {
                                let item = {};
                                let params = workExp[i].split('**')
                                if (params.length < 5) {
                                    // 不够5个说明是无效的
                                    continue;
                                }
                                item.company_name = params[0];
                                item.job_title = params[1];
                                let jobCates = params[2].split('>');
                                if (jobCates.length < 3) {
                                    // 无法形成三级分类
                                    continue;
                                }
                                item.jobscate1 = jobCates[0];
                                item.jobscate2 = jobCates[1];
                                item.jobscate3 = jobCates[2];
                                let time = params[3].split('-');
                                if (time.length < 2) {
                                    // 无法形成在职时间段
                                    continue;
                                }
                                item.start_time = Math.round(new Date(time[0]).getTime() / 1000);
                                item.end_time = Math.round(new Date(time[1]).getTime() / 1000);
                                item.job_content = params[4];
                                data.work_experience.push(item)
                            } catch (ex) {
                                data.errMsg += data.errMsg.length > 0 ? ` | 工作经历${i + 1}存在问题：${ex}` : `工作经历${i + 1}存在问题：${ex}`
                            }
                        }
                    }
                    // 如果存在培训经历
                    if (row['培训经历'] != undefined) {
                        let trainingExp = row['培训经历'].split('||');
                        for (let i = 0; i < trainingExp.length; i++) {
                            try {
                                let item = {};
                                let params = trainingExp[i].split('**');
                                if (params.length < 4) {
                                    continue;
                                }
                                item.mechanism = params[0];
                                item.project_name = params[1];
                                let time = params[2].split('-');
                                if (time.length < 2) {
                                    // 无法形成培训时间段
                                    continue;
                                }
                                item.start_time = Math.round(new Date(time[0]).getTime() / 1000);
                                item.end_time = Math.round(new Date(time[1]).getTime() / 1000);
                                item.training_content = params[3];
                                data.training_experience.push(item)
                            } catch (ex) {
                                data.errMsg += data.errMsg.length > 0 ? ` | 培训经历${i + 1}存在问题：${ex}` : `培训经历${i + 1}存在问题：${ex}`
                            }
                        }
                    }
                    // 如果存在项目经历
                    if (row['项目经历'] != undefined) {
                        let projectExp = row['项目经历'].split('||');
                        for (let i = 0; i < projectExp.length; i++) {
                            try {
                                let item = {};
                                let params = projectExp[i].split('**');
                                if (params.length < 4) {
                                    continue;
                                }
                                item.project_name = params[0];
                                item.project_role = params[1];
                                let time = params[2].split('-');
                                if (time.length < 2) {
                                    // 无法形成项目时间段
                                    continue;
                                }
                                item.start_time = Math.round(new Date(time[0]).getTime() / 1000);
                                item.end_time = Math.round(new Date(time[1]).getTime() / 1000);
                                item.project_link = params[3];
                                item.project_content = params[4];
                                data.project_experience.push(item)
                            } catch (ex) {
                                data.errMsg += data.errMsg.length > 0 ? ` | 项目经历${i + 1}存在问题：${ex}` : `项目经历${i + 1}存在问题：${ex}`
                            }
                        }
                    }
                    // 如果存在证书
                    if (row['获得证书'] != undefined) {
                        let certs = row['获得证书'].split('||');
                        for (let i = 0; i < certs.length; i++) {
                            data.certificate.push(certs[i]);
                        }
                    }
                    // 如果存在语言能力
                    if (row['语言能力'] != undefined) {
                        let langs = row['语言能力'].split('||');
                        for (let i = 0; i < langs.length; i++) {
                            data.language_ability.push(langs[i]);
                        }
                    }
                    // 如果存在证书
                    if (row['特长标签'] != undefined) {
                        let label = row['特长标签'].split('||');
                        for (let i = 0; i < label.length; i++) {
                            data.specialty_label.push(label[i]);
                        }
                    }
                    return data;
                }
                catch (ex) {
                    data.invalid = true;
                    return data;
                }
            },
            getResumeInfo(row, expandedRows) {
                if (row.resume_info) return;
                $.getJSON('/getResumeInfo/' + row.id, function (ret) {
                    if (ret) {
                        if (ret.code === 0) {
                            row.resume_info = 1;
                            row.data = ret.data;
                        } else {
                            row.resume_info = 2;
                            XYBase.msg(ret.msg);
                        }
                    } else {
                        XYBase.error(XYBase.config.system_network_error);
                    }
                });
            },
            checkSelectable(row, index) {
                let result = true;
                if (row.invalid == undefined || row.invalid) {
                    result = false;
                }
                return result;
            },
            checkAllData() {
                let _this = this;
                hwdn = XYBase.openloading('数据核验中，请勿刷新网页或关闭浏览器');
                this.checkAllDataAjax(0);
            },
            checkAllDataAjax(i) {
                let _this = this;
                let target = _this.tableData[i];
                if (!target) return hwdn.close();
                i++;
                if (target.invalid) {
                    return _this.checkAllDataAjax(i);
                }
                $.ajax({
                    url: '/resume/verify',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(target),
                    success(res) {
                        if (res.code != undefined && res.code == 0) {
                            target.invalid = false;
                        } else {
                            target.invalid = true;
                            target.errMsg = res.msg ?? '网络错误';
                        }
                        _this.checkAllDataAjax(i);
                    },
                    error() {
                        _this.checkAllDataAjax(i);
                    }
                });
            },
            showErrorReason(row) {
                console.log(row.errMsg)
            },
            submitResumes() {
                let _this = this;
                for (let i = 0; i < _this.tableData.length; i++) {
                    $.ajax({
                        url: '/resume/importResume',
                        type: 'POST',
                        contentType: 'application/json;charset=utf-8;',
                        data: JSON.stringify(_this.tableData[i]),
                        success(res) {
                            if (res.code != undefined) {
                                if (res.code == 0) {
                                    _this.successNumber++;
                                } else {
                                    _this.tableData[i].invalid = true;
                                    _this.tableData[i].errMsg = res.msg;
                                }
                            } else {
                                _this.tableData[i].errMsg = '网络错误';
                            }
                        }
                    })
                }
            },
            showSuccessNumber() {
                XYBase.msg(`本次已成功导入${this.successNumber}份简历`);
            },
            initHtml() {
                this.fileReader = new FileReader();
            },
        },
        mounted() {
            this.initHtml()
        },
    });
    $(function () {
        reloadWindowSize();
        $(window).resize(function () {
            reloadWindowSize();
        });
    });
    function reloadWindowSize(argument) {
        var winW = $(window).width();
        if (winW <= 576) {
            vm.labelPosition = 'top';
        } else {
            vm.labelPosition = 'right';
        }
    }
</script>
{/block}